#!/bin/bash
#
# Conv-host for MPI:
#  Translates +pN-style conv-host options into
# mpirun -npN options.

export FROM_CHARMRUN='1'

args=""

# Arguments that need to be passed to the charm application, not mpirun (e.g. ++quiet)
charm_args=""
pes=1
ppn=1
QUIET=0
XTERM='xterm'
DEBUG=0
DEBUG_NO_PAUSE=0
DEBUGGER='gdb'

while [ $# -gt 0 ]
do
    case $1 in
	+ppn|++ppn)
	    args=$args" +ppn "$2
	    ppn=$2
	    shift
	    ;;
	+ppn[0-9]*)
	    args=$args" "$1
	    ppn=$(echo "$1" | awk '{print substr($1,5)}')
	    ;;
	++ppn[0-9]*)
	    args=$args" "$1
	    ppn=$(echo "$1" | awk '{print substr($1,6)}')
	    ;;
	+p)
	    pes=$2
	    shift
	    ;;
	+pemap)
	    args="$args $1 $2"
	    shift
	    ;;
	+p[0-9]*)
	    pes=$(echo "$1" | awk '{print substr($1,3)}')
	    ;;
        -machinefile)
	    args=" $1 $2 $args"
	    shift
	    ;;
	++quiet)
	    QUIET=1
	    ;;
	++no-quiet)
	    QUIET=0
	    ;;
	++local|++no-local)
		# Ignored (unsupported by MPI layer)
		;;
	++xterm)
		XTERM=$2
		shift
		;;
	++debug)
		DEBUG=1
		;;
	++no-debug)
		DEBUG=0
		;;
	++debug-no-pause)
		DEBUG_NO_PAUSE=1
		;;
	++no-debug-no-pause)
		DEBUG_NO_PAUSE=0
		;;
	++debugger)
		DEBUGGER=$2
		shift
		;;
	*)
	    args=$args" "$1
	    ;;
    esac
    shift
done

test $QUIET -eq 1 && charm_args=$charm_args" "++quiet

args=$args" "$charm_args

if [ "$DEBUG" = '1' ] || [ "$DEBUG_NO_PAUSE" = '1' ]
then
  DEBUG_RUN='-ex r'
  DEBUG_POSTFIX='--args'
  if [ "$DEBUGGER" = 'lldb' ]
  then
    DEBUG_RUN='-o r'
    DEBUG_POSTFIX='--'
  fi

  args="$DEBUG_POSTFIX $args"
  [ "$DEBUG_NO_PAUSE" = '1' ] && args="$DEBUG_RUN $args"
  args="$XTERM -e $DEBUGGER $args"
fi

rem=$((pes % ppn))
quot=$((pes / ppn))
if [ $rem -ne 0 ];
then
    echo "p = $pes should be a multiple of ppn = $ppn"
    exit 1
else
    pes=$quot
fi

test $QUIET -eq 0 && echo && echo "Running on $pes processors: $args"


mpiexec_cmd=$(which mpiexec 2>/dev/null)
if test -n "$mpiexec_cmd"
then
    test $QUIET -eq 0 && echo "charmrun> $mpiexec_cmd -n $pes $args"
    test $QUIET -eq 0 && echo
    # shellcheck disable=SC2086
    "$mpiexec_cmd" -n $pes $args
else
    echo "Don't know how to run MPI program."
    exit 1
fi
